﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;

namespace LabChecker.Models
{    
    public class TestCase
    {
        public int Id { get; set; }
        [Required]
        [MaxLength]
        public string Input { get; set; }
        [Required]
        [MaxLength]
        public string Answer { get; set; }
        [Required]
        public bool IsExample { get; set; }
        [Required]        
        public int Index { get; set; }
        [Required]        
        [IgnoreDataMember]
        public virtual Task Task { get; set; }
        public string ErrorMessage { get; set; }

        public virtual CheckResults.TestCaseBase Check(string output)
        {
            string[] answerLines = GetLines(Answer);
            string[] outputLines = GetLines(output);
            if (answerLines.Length != outputLines.Length)
            {
                return new CheckResults.TestCase.WrongAnswer(output, Answer, ErrorMessage);
            }
            for (int i = 0; i < answerLines.Length; i++)
            {
                if (!CompareOneLine(answerLines[i], outputLines[i]))
                {
                    return new CheckResults.TestCase.WrongAnswer(output, Answer, ErrorMessage);
                }
            }
            return new CheckResults.TestCase.Accepted();
        }

        private string[] GetLines(string text)
        {
            return text.Replace("\r\n", "\n").TrimEnd('\n').Split('\n');
        }

        private bool CompareOneLine(string outputLine, string answerLine)
        {
            return PrepareLine(outputLine).Equals(PrepareLine(answerLine));
        }

        private string PrepareLine(string line)
        {
            return line.TrimEnd(' ');
        }
    }
}